<template>
    <div class="component">
    <Breadcrumb :menulist="[`${componentType == 1 ? '项目' : '产品'}`, '模型']" v-on:changeSolution="changeSolution" :componentType="componentType"></Breadcrumb>
    <el-card class="box-card" shadow="hover">
        <div slot="header" class="tabHeader">
            <el-button class="openComp" type="text" @click="showSelectComp">打开模型列表</el-button>
            <span>
              {{componentSelect}}
            </span>

            <el-button class="addPro" icon="el-icon-circle-plus" type="primary" @click="showAddPro">添加模型</el-button>
            <!--
              <el-button class="addPro" icon="el-icon-circle-plus" type="primary" v-if="activeName === 'modelProperty'" @click="showAddModel">添加模型属性</el-button>
            <el-button class="addPro" icon="el-icon-circle-plus" type="primary" v-if="activeName === 'modelProperty'" @click="showAddPro">批量添加模型属性</el-button>
            -->
          
        </div>

      <el-tabs class="modelTabs">
          <el-table
              :data="tableData"
              max-height="600"
              line-height="50"
              border
              :header-cell-style='headerStyle'
              style="width: 100%">
              <!--
                <el-table-column
                    prop="modelId"
                    label="模型ID"
                    width="100"
                    align="center">
                </el-table-column>
              -->
              <el-table-column
                  prop="modelCode"
                  label="模型编码"
                  width="200"
                  align="center">
              </el-table-column>
              <el-table-column
                  prop="modelName"
                  align="center"
                  width="200"
                  label="模型名称">
              </el-table-column>
              <el-table-column
                  prop="baseModelName"
                  align="center"
                  width="100"
                  label="基础模型">
              </el-table-column>
              <el-table-column
                  prop="parentModelName"
                  align="center"
                  width="100"
                  label="父模型">
              </el-table-column>
              <el-table-column
                  prop="componentName"
                  align="center"
                  width="200"
                  label="所属组件">
              </el-table-column>
              <el-table-column
                  prop="moduleName"
                  align="center"
                  width="200"
                  label="所属模块">
              </el-table-column>
              <el-table-column
                  prop="topSolutionName"
                  align="center"
                  width="100"
                  label="所属产品">
              </el-table-column>
              <el-table-column
                  prop="isSystem"
                  align="center"
                  width="100"
                  label="是否系统">
                  <template slot-scope="scope">
                      <span class="percentFont">{{scope.row.isSystem ? '是' : '否'}}</span>
                  </template>
              </el-table-column>
              <el-table-column
                  prop="isEntity"
                  align="center"
                  width="100"
                  label="是否实体">
                  <template slot-scope="scope">
                      <span class="percentFont">{{scope.row.isEntity ? '是' : '否'}}</span>
                  </template>
              </el-table-column>
              <el-table-column
                  prop="isExtend"
                  align="center"
                  width="100"
                  label="是否扩展">
                  <template slot-scope="scope">
                      <span class="percentFont">{{scope.row.isExtend ? '是' : '否'}}</span>
                  </template>
              </el-table-column>
              <el-table-column
                  prop="tableName"
                  align="center"
                  width="100"
                  label="表名">
              </el-table-column>
              <el-table-column
                  prop="viewName"
                  align="center"
                  width="100"
                  label="视图名">
              </el-table-column>
              <el-table-column
                  prop="selectSql"
                  align="center"
                  width="100"
                  label="查询语句">
              </el-table-column>
              <el-table-column
                  prop="description"
                  align="center"
                  width="100"
                  label="描述">
              </el-table-column>
              <el-table-column
                  prop="databaseName"
                  align="center"
                  width="250"
                  label="操作">
                  <template slot-scope="scope">
                    <el-button size="mini" @click="handleBuild(scope.$index, scope.row)">生成属性</el-button>
                    <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button size="mini" slot="reference" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                    <el-button size="mini" @click="handleModelattributes(scope.$index, scope.row)">进入属性列表</el-button>
                  </template>
              </el-table-column>
          </el-table>

      </el-tabs>
      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="slot, total, sizes, prev, pager, next, jumper"
        :total="total">
        <el-button icon="el-icon-refresh" type="primary" style="margin-right: 10px; background: #409EFF; color:#fff" @click="getModelsList(null)"></el-button>
      </el-pagination>
    </el-card>


    <el-drawer
        title="模型列表"
        :visible.sync="showComp"
        direction="ltr"
        :with-header="false"
        size="30%">
        <div class="drawerTitle">选择模型列表</div>
        <el-tree
          :data="treeData"
          node-key="id"
          class="tree"
          :props="treedefaultProps"
          @node-click="handleNode">
        </el-tree>

    </el-drawer>



    <!-- 添加模型 -->
    <el-dialog :title="dialogTitle"  :visible.sync="dialogFormVisible" :close-on-click-modal="false" width="60%">
      <el-row>
        <el-form :model="form"  :rules="rules" ref="form" label-width="100px">
          <el-col :span="24" v-if="dialogTitle === '删除模型'">
            <el-form-item label="删除提示信息">
              <div style="color: #d93a49;">{{deleteCheckContent}}</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
              <el-form-item label="模型编码" prop="modelCode">
                <el-input v-model="form.modelCode" placeholder="请输入模型编码" :disabled="deleteDisabled || dialogTitle == '编辑模型'"></el-input>
              </el-form-item>
              <el-form-item label="模型名称" prop="modelName">
                <el-input v-model="form.modelName" placeholder="请输入模型名称" :disabled="deleteDisabled"></el-input>
              </el-form-item>
              <el-form-item label="基础模型" prop="baseModelId">
                <el-select v-model="form.baseModelId" placeholder="请选择基础模型" :disabled="deleteDisabled" style="width: 100%;">
                  <el-option value="4194304000" label="业务实体"></el-option>
                  <el-option value="4194305000" label="业务档案"></el-option>
                  <el-option value="4194306000" label="业务单据"></el-option>
                  <el-option value="4194303000" label="模型基类"></el-option>
                </el-select>
              </el-form-item>
              <!--
               <el-form-item label="父模型" prop="parentModelName">
                <el-input v-model="form.parentModelName" placeholder="请输入父模型" disabled></el-input>
              </el-form-item>
              -->
              <el-form-item label="所属组件" prop="componentName">
                <el-input v-model="form.componentName" placeholder="请选择所属组件" disabled></el-input>
              </el-form-item>
              <el-form-item label="所属模块" prop="moduleName">
                <el-input v-model="form.moduleName" placeholder="请选择所属模块" disabled></el-input>
              </el-form-item>
              <el-form-item label="所属项目" prop="solutionName" v-if="componentType===1">
                <el-input v-model="form.solutionName" placeholder="请选择所属项目" disabled></el-input>
              </el-form-item>
              <el-form-item label="所属产品" prop="topSolutionName">
                <el-input v-model="form.topSolutionName" placeholder="请选择所属产品" disabled></el-input>
              </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否系统" prop="isSystem">
                <el-radio-group v-model="form.isSystem" :disabled="deleteDisabled">
                  <el-radio label="1">是</el-radio>
                  <el-radio label="0">否</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="是否实体" prop="isEntity">
                <el-radio-group v-model="form.isEntity" @change="chengeEntity" :disabled="deleteDisabled">
                  <el-radio label="1">是</el-radio>
                  <el-radio label="0">否</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="是否扩展" prop="isExtend">
                <el-radio-group v-model="form.isExtend" :disabled="form.isEntity === '0' || deleteDisabled">
                  <el-radio label="1">是</el-radio>
                  <el-radio label="0">否</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="表名" prop="tableName">
              <el-input v-model="form.tableName" placeholder="请输入表名" @change="onChangeTableName" :disabled="deleteDisabled"></el-input>
            </el-form-item>
            <el-form-item label="视图名" prop="viewName">
              <el-input v-model="form.viewName" placeholder="请输入视图名" :disabled="deleteDisabled"></el-input>
            </el-form-item>
            <el-form-item label="查询语句" prop="selectSql">
                <el-input type="textarea" v-model="form.selectSql" :disabled="deleteDisabled"></el-input>
                <el-button plain style="margin-top: 10px;">检查</el-button>
            </el-form-item>
            <el-form-item label="描述" prop="description">
                <el-input v-model="form.description" :disabled="deleteDisabled"></el-input>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="dialogTitle === '添加模型'" @click="handleSave('form')">保 存</el-button>
        <el-button type="primary" v-if="dialogTitle === '编辑模型'" @click="__handleEdit('form')">保 存</el-button>
        <el-button type="primary" plain v-if="dialogTitle === '添加模型'" @click="resetForm('form')">清 除</el-button>
        <el-button type="danger" plain v-if="dialogTitle === '删除模型'" @click="__handleDelete('form')">删 除</el-button>
        <el-button @click="handleCancel('form')">取 消</el-button>
      </div>
    </el-dialog>


    </div>
</template>


<script>
import {request, url} from "@/api/request";
import Breadcrumb from "@/components/Breadcrumb.vue";

export default {
  name: "model",
  components: {
    Breadcrumb
  },
  props: {
    componentType: {
        type: Number,
        default: 1,//1组件，2产品
    },
  },
  data() {
    return {
      headerStyle: {
        "line-height": "40px"
      },
      tableData: [],
      formLabelWidth: "100px",
      dialogFormVisible: false,
      form: {
        modelCode: "",
        modelName: "",
        baseModelId: "",
        baseModelName: "",
        parentModelId: "",
        // parentModelName: "",
        componentId: "",
        componentName: "",
        moduleId: "",
        moduleName: "",
        solutionId: "",
        solutionName: "",
        topSolutionId: "",
        topSolutionName: "",
        isSystem: '0',
        isEntity: '1',
        isExtend: '0',
        tableName: "",
        viewName: "",
        selectSql: "",
        description: "",
        modelId: "",
      },
      rules: {
        modelCode: [
          { required: true, message: '请输入模型编码', trigger: 'change' },
        ],
        modelName: [
          { required: true, message: '请输入模型名称', trigger: 'change' },
        ],
        baseModelId: [
          { required: true, message: '请输入基础模型名称', trigger: 'change' },
        ],
      },
      showComp: false,
      treeData: [],
      treedefaultProps: {
        children: 'childs',
        label: 'label'
      },
      componentSelect: '-',
      defaultComponent: '',
      defaultComponentName: '',
      pageNum: 10,
      pageSize: 10,
      total: 0,
      dialogTitle: '添加模型',
      deleteCheckContent: '',
      deleteDisabled: false,

    };
  },

  created() {

    if (this.$store.state.solution_global) {
      this.getTreesList();
      let option = this.getLocationParams(location.href.split('?')[1]);
      if (option) {
        this.defaultComponent = option.defaultComponent;
        this.componentSelect = decodeURIComponent(option.componentSelect);
        this.getModelsList();
      }
      
    }
  },

  methods: {
    // 切换 solution 
    changeSolution() {
      this.getTreesList();
    },
    // 组件数 tree
    getTreesList() {
      let solutionId = this.$store.state.solution_global.solutionId;
      request(`${url.navigationtree}/${solutionId}`,{
        method:'GET',
        data: {}
      },res=>{
        let newData = res.data.root.childs;
        // let treedata = [];
        // newData.map((item, i) => {
        //   item.childs.map((cell, j) => {
        //     cell.disabled = true
        //     if (cell.navigationType.displayName === 'Component') {
        //       delete cell.childs
        //     }
        //   })
        // })

        let d = this.filterTree(newData);
        this.treeData = d;
        
      })
    },

    // 过滤 tree 数据重新整合
    filterTree(data) {
      if(!data) {
        return false;
      }
      return data.map(item => {
        if (item.childs) {
          this.filterTree(item.childs);
        }
        item.label = `${item.label}（${item.navigationType.displayName}）`
        return item;
      }).filter(item => item);
    },


    // 查询列表
    getModelsList(data) {
      if (!this.$store.state.solution_global) {
        return this.$message({
          message: '请先选择一个解决方案',
          type: 'warning'
        });
      }
      if (this.defaultComponent === '') {
        this.$message({
          message: '请先选择右侧组件',
          type: 'warning'
        });
        return false;
      }
      let componentId = '';
      let modelId = '';
      console.log(data);
      if (data) {
        if (data.navigationType.code == '3') {
          componentId = '';
          modelId = data.id;
        } else {
          componentId = this.defaultComponent;
          modelId = null;
        }
      } else {
        componentId = this.defaultComponent;
      }

      let solutionId = this.$store.state.solution_global.solutionId;
      let params = {
        currentPage: this.pageNum,
        rows: this.pageSize,
        solutionId: solutionId,
        modelId: modelId,
      }
      request(`${url.modelsList}/${componentId}`,{
          method:'GET',
          data: params
      },res=>{
          this.tableData = res.data.list;
          this.pageNum = res.data.pageNum;
          // this.pageSize = res.data.pageSize;
          this.total = res.data.total;
      })
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.pageNum = 1;
      this.getModelsList();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.getModelsList();
    },

    showAddPro() {
      if (this.defaultComponent === '') {
        this.$message({
          message: '请先选择右侧组件',
          type: 'warning'
        });
        return false;
      }
      this.dialogTitle = '添加模型';
      this.dialogFormVisible = true;
      this.deleteDisabled = false;
      this.getModelsDefault();
    },

    // 获取默认组件
    getModelsDefault() {
      request(`${url.modelsDefault}/${this.defaultComponent}`,{
          method:'GET',
          data: {}
        },res=>{
          let data = res.data;
          this.form.parentModelId = data.moduleId;
          // this.form.parentModelName = data.moduleName;
          this.form.componentId = data.componentId;
          this.form.componentName = data.componentName;
          this.form.moduleId = data.moduleId;
          this.form.moduleName = data.moduleName;
          this.form.solutionId = data.solutionId;
          this.form.solutionName = data.solutionName;
          this.form.topSolutionId = data.topSolutionId;
          this.form.topSolutionName = data.topSolutionName;
        })
    },

    showSelectComp() {
      this.showComp = true
    },

    handleNode(data, parent) {
      // if (data.navigationType.displayName === "Component" || data.navigationType.displayName === "Model") {
      if (data.navigationType.displayName === "Component") {
        this.showComp = false;
        this.componentSelect = ""; //  初始化
        this.defaultComponent = data.id; //  设置选中的module
        this.defaultComponentName = data.label; //  设置选中的moduleName
        
        this.getTreeNode(parent);
        console.log(data)
        console.log(parent)
        this.getModelsList(data);
        let b = encodeURIComponent(this.componentSelect);
        this.$router.push({path: `model?defaultComponent=${this.defaultComponent}&componentSelect=${b}`})

      } else {
        this.$message({
          // message: '请先选择组件(Component)或者模型(Model)',
          message: '请先选择组件(Component)',
          type: 'warning'
        });
      }
    },

    //获取当前树节点和其父级节点
    getTreeNode(node){
      if (node.parent) {
          this.componentSelect = `${node.label} ${this.componentSelect ? '>':''} ${this.componentSelect}`;
          this.getTreeNode(node.parent); //递归
      }
    },

    chengeEntity(value) {
      this.form.isEntity = value;
      if (value === '0') {
        this.form.isExtend = '0';
      }
    },

    onChangeTableName(value) {
      console.log(value)
      if (value) {
        this.form.viewName = `${value}_view`;
      } else {
        this.form.viewName = '';
      }
    },

    // 保存
    handleSave(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let parmas = {
            modelCode: this.form.modelCode,
            modelName: this.form.modelName,
            baseModelId: this.form.baseModelId,
            // baseModelName: this.form.baseModelName,
            parentModelId: this.form.parentModelId,
            // parentModelName: this.form.parentModelName,
            componentId: this.form.componentId,
            componentName: this.form.componentName,
            moduleId: this.form.moduleId,
            moduleName: this.form.moduleName,
            solutionId: this.form.solutionId,
            solutionName: this.form.solutionName,
            topSolutionId: this.form.topSolutionId,
            topSolutionName: this.form.topSolutionName,
            isSystem: this.form.isSystem,
            isEntity: this.form.isEntity,
            isExtend: this.form.isExtend,
            tableName: this.form.tableName,
            viewName: this.form.viewName,
            selectSql: this.form.selectSql,
            description: this.form.description,
          };
          request(`${url.models}`,{
              method:'POST',
              data: parmas
          },res=>{
              this.$message({
                message: res.message,
                type: 'success'
              });
              this.dialogFormVisible = false;
              this.getModelsList();
              this.$refs.form.resetFields();  // 重置 form表单
          })
        } else {
          return false;
        }
      });
    },

    resetForm(formName) {
      // this.$refs[formName].resetFields();
      this.form.modelCode = "";
      this.form.modelName = "";
      this.form.baseModelId = "";
      this.form.baseModelName = "";
      this.form.tableName = "";
      this.form.viewName = "";
      this.form.selectSql = "";
      this.form.description = "";
      this.form.modelId = "";
    },

    handleCancel(formName) {
      this.$refs[formName].resetFields();
      this.dialogFormVisible = false;
    },

    handleModelattributes(index, row) {
      this.$router.push({path: `modelAttributes?modelId=${row.modelId}&solutionId=${row.solutionId}`})
    },

    handleBuild(index, row) {
       this.$confirm('确认生成属性字段吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let modelId = row.modelId;
          request(`${url.modelsCreateattibute}/${modelId}`,{
              method:'POST',
              data: {}
          },res=>{
              this.$message({
                message: res.message,
                type: 'success'
              });
              this.dialogFormVisible = false;
          })
        }).catch(() => {

        });
    },

    // 编辑
    handleEdit(index, row) {
      console.log(row);
      this.dialogTitle = '编辑模型';
      this.dialogFormVisible = true;
      this.form.modelCode = row.modelCode;
      this.form.modelName = row.modelName;
      this.form.baseModelId = row.baseModelId;
      this.form.baseModelName = row.baseModelName;
      this.form.parentModelId = this.defaultComponent;
      // this.form.parentModelName = this.defaultComponentName;
      this.form.componentId = row.componentId;
      this.form.componentName = row.componentName;
      this.form.moduleId = row.moduleId;
      this.form.moduleName = row.moduleName;
      this.form.solutionId = row.solutionId;
      this.form.solutionName = row.solutionName;
      this.form.topSolutionId = row.topSolutionId;
      this.form.topSolutionName = row.topSolutionName;
      this.form.isSystem = String(row.isSystem);
      this.form.isEntity = String(row.isEntity);
      this.form.isExtend = String(row.isExtend);
      this.form.tableName = row.tableName;
      this.form.viewName = row.viewName;
      this.form.selectSql = row.selectSql;
      this.form.description = row.description;
      this.form.modelId = row.modelId;

    },

    __handleEdit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(this.form)
          let parmas = {
              modelId: this.form.modelId,
              modelCode: this.form.modelCode,
              modelName: this.form.modelName,
              baseModelId: this.form.baseModelId,
              // baseModelName: this.form.baseModelName,
              parentModelId: this.form.parentModelId,
              // parentModelName: this.form.parentModelName,
              componentId: this.form.componentId,
              componentName: this.form.componentName,
              // moduleId: this.form.moduleId,
              // moduleName: this.form.moduleName,
              moduleName: '工艺管理',
              moduleId: '202072979171966976',
              solutionId: this.form.solutionId,
              solutionName: this.form.solutionName,
              topSolutionId: this.form.topSolutionId,
              topSolutionName: this.form.topSolutionName,
              isSystem: this.form.isSystem,
              isEntity: this.form.isEntity,
              isExtend: this.form.isExtend,
              tableName: this.form.tableName,
              viewName: this.form.viewName,
              selectSql: this.form.selectSql,
              description: this.form.description,
              modelId: this.form.modelId,
          };
          console.log(parmas)
          request(`${url.models}/${this.form.modelId}`,{
              method:'PUT',
              data: parmas
          },res=>{
              this.$message({
                message: res.message,
                type: 'success'
              });
              this.dialogFormVisible = false;
              this.getModelsList();
              this.$refs.form.resetFields();  // 重置 form表单
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },


    // 删除
    handleDelete (index, row) {
      console.log(row)
      this.dialogTitle = '删除模型';
      this.deleteDisabled = true;
      this.dialogFormVisible = true;

      this.form.modelCode = row.modelCode;
      this.form.modelName = row.modelName;
      this.form.baseModelId = row.baseModelId;
      this.form.baseModelName = row.baseModelName;
      this.form.parentModelId = this.defaultComponent;
      // this.form.parentModelName = this.defaultComponentName;
      this.form.componentId = row.componentId;
      this.form.componentName = row.componentName;
      this.form.moduleId = row.moduleId;
      this.form.moduleName = row.moduleName;
      this.form.solutionId = row.solutionId;
      this.form.solutionName = row.solutionName;
      this.form.topSolutionId = row.topSolutionId;
      this.form.topSolutionName = row.topSolutionName;
      this.form.isSystem = String(row.isSystem);
      this.form.isEntity = String(row.isEntity);
      this.form.isExtend = String(row.isExtend);
      this.form.tableName = row.tableName;
      this.form.viewName = row.viewName;
      this.form.selectSql = row.selectSql;
      this.form.description = row.description;
      this.form.modelId = row.modelId;
      this.deleteCheck(row.modelId);
      
    },

    // check delete
    deleteCheck(modelId) {
      request(`${url.modelsDeleteCheck}/${modelId}`,{
          method:'GET',
          data: {
            solutionId: this.form.solutionId,
            isSystem: this.form.isSystem
          }
      },res=>{
        this.deleteCheckContent = res.data + res.message;
      })
    },

    //  确认删除 
    __handleDelete () {
      let modelId = this.form.modelId;
      request(`${url.models}/${modelId}`,{
          method:'DELETE',
          data: {}
      },res=>{
          this.dialogFormVisible = false;
          this.$message({
            message: '删除成功！',
            type: 'success'
          });
          this.getModelsList();
          this.$refs.form.resetFields();  // 重置 form表单
      })
    }


  }
};
</script>

<style scoped>

.modelTabs {
  padding: 0 20px;
}

.addPro {
  float: right;
  margin-right: 20px;
}

.openComp {
  margin-left: 20px;
}

.drawerTitle {
  line-height: 70px;
  font-size: 20px;
  margin-left: 30px;
}

.tree {
  margin-left: 30px;
  
}
</style>
